from sanic import Sanic
from sanic.exceptions import NotFound
from sanic.response import text
import url_router
import database
from config import *
from sanic_ext import Extend
import time
import asyncio
from datetime import datetime
from sanic.response import json
from sanic.log import logger

app = Sanic("MyApp")

# 注册服务启动之前的监听器，用于服务器前的的相关配置，如初始化数据库连接，redis连接等
@app.listener("before_server_start")
async def setup(app, loop):
    db = database.MysqlHelper('flask_games')
    # 将数据库manager注册到app的ctx上下文中
    app.ctx.db = db
    asyncio.create_task(my_timer())  # 创建协程任务
    print("连接mysql上线文")

# 定义定时任务
async def my_timer():
    while True:
        print("定时任务运行中...")
        # 这里可以放置你的定时任务逻辑
        print(app.ctx.db)
        # 例如数据库操作，发送消息等
        await asyncio.sleep(60*60*24)  # 每隔天执行一次


app.static('/static', './static')

app.config.CORS_ORIGINS = url

Extend(app)

for i in url_router.url_router():
    app.add_route(*i)  # i*  *会把元组去除 ()

@app.exception(NotFound)
def ignore_404s(request, exception):
    return text("Yep, I totally found the page: {}".format(request.url))


@app.middleware("request")
async def extract_user(request):
    # 排查ip
    db = app.ctx.db
    app.ctx.token = request.headers.get('Authorization')

    # 判断是否是公告路由
    # print(request.url,url_list)

    if request.url in url_list or request.url  ==  'http://127.0.0.1:8090/basic-api/login':
        pass
    else:

        if request.headers.get('Authorization') and request.headers.get('CHANNEL') != 'wechat':
            #  查看token用户
            sql = """
                select user_id,login_date,timestamp from  token where token=%s
            """

            token = db.find_one(sql,(app.ctx.token))

            try:
                login_date = int(time.mktime(time.strptime(datetime.strftime(token[1], "%Y-%m-%d %H:%M:%S"), "%Y-%m-%d %H:%M:%S")))
            except:
                return json({'code':'001','message':'token失效'})

            if token and ((int(time.time())) - (login_date ) < int(eval(token[2]))) :

                app.ctx.user_id = token[0]
                # 切换角色使用

                sql_role = f"""
                    select select_role_code from a_users where user_id='{token[0]}'
                """
                role_code = db.find_one(sql_role)
                app.ctx.select_role_code = role_code[0]

            else:
                # print("拦截", request.url)
                return json({'code':'001','message':'token失效'})
        elif request.headers.get('CHANNEL') == 'wechat' or request.headers.get('channel') == 'wechat':
            #  查看token用户
            USER_SERVICE_TOKEN = request.headers.get('USER_SERVICE_TOKEN')
            sql = f"""
                select user_id from a_users where USER_SERVICE_TOKEN='{USER_SERVICE_TOKEN}'
            """

            user_id = db.find_one(sql)
            if user_id:
                app.ctx.user_id = user_id[0]
            else:
                # print("拦截", request.url)
                return json({'code': 202, 'message': '未监测道商家信息!'})
            try:
                if request.headers.get('Authorization'):
                    sql = f"""
                        select id from c_users where openid='{request.headers.get('Authorization')}'
                    """
                    c_user_id = db.find_one(sql)

                    if c_user_id[0]:
                        app.ctx.c_user_id = c_user_id[0]
                        app.ctx.openid = request.headers.get('Authorization')
            except Exception as error:
                pass

        else:
            print("拦截", request.url)

            return json({'code': 504, 'message': '非法用户'})


@app.on_response()  # 跨域头文件处理
async def set_headers(request, response):

    response.headers["Server"] = "Microsoft-IIS/6/0"
    response.headers["X-Powered-By"] = "ASP.NET"
    response.headers["Content-Type"] = "application/json;charset=UTF-8"
    response.headers["Access-Control-Allow-Origin"] = "*"
    response.headers["Access-Control-Allow-Headers"] = "*"
    response.headers["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS, DELETE"
    response.headers["Server"] = "Microsoft-IIS/6/0"

if __name__ == '__main__':
    # app.run(port=8090,host="0.0.0.0",debug=DEBUG,access_log=ACCESS_LOG,workers=4)
    app.run(port=8090,host="0.0.0.0",debug=DEBUG,access_log=ACCESS_LOG)
